package com.aurora.oa.work.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.listener.OnRequestApproveListListener;
import com.aurora.oa.listener.OnRequestNoticeListListener;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.work.adapter.ApproveAdapter;
import com.aurora.oa.work.adapter.NoticeAdapter;
import com.aurora.oa.work.bean.ApproveListBean;
import com.aurora.oa.work.bean.NoticeBean;

import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.home.adapter.ArticleAdapter;
import com.aurora.oa.home.bean.ArticleBean;
import com.aurora.oa.home.presenter.ArticalListActivityPresenter;
import com.aurora.oa.home.presenter.ArticalListActivityPresenterImpl;
import com.aurora.oa.home.view.ArticalDetailActivity;
import com.aurora.oa.home.view.ArticalListActivityView;
import com.aurora.oa.listener.OnRequestNoticeListListener;
import com.aurora.oa.model.RequestHttpModel;
import com.aurora.oa.model.RequestHttpModelImpl;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.work.adapter.NoticeAdapter;
import com.aurora.oa.work.bean.NoticeBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/24 0024.
 */
public class ApproveListFragment extends Fragment{
    int type;
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    LinearLayoutManager layoutManager;
    boolean isLoading;
    private int whitchPage =1;
    private List<ApproveListBean> data = new ArrayList<>();
    private ApproveAdapter adapter ;
    private Handler handler = new Handler();
    RequestHttpModel requestHttpModel = new RequestHttpModelImpl();
    Activity mAct;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAct = getActivity();
        if (savedInstanceState == null) {
            type = getArguments().getInt("approve_type");
        } else {
            type = savedInstanceState.getInt("approve_type");
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_approve_list,container,false);
        initView(view);
        getData();
        return view;
    }

    private void initView(View view) {

        swipeRefreshLayout = (SwipeRefreshLayout)view. findViewById(R.id.SwipeRefreshLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue,R.color.white);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage = 1;
                        data.clear();
                        getData();
                    }
                }, 0);
            }
        });
        layoutManager = new LinearLayoutManager(mAct);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ApproveAdapter(mAct,data,true);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new ApproveAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mAct,ApproveDetailActivity.class);
                intent.putExtra("id",data.get(position).getId());
                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");
                loadMoreData();
            }
        });

    }

    //请求数据
    private void getData(){
        ///approval/page/{nowpage}/{approvalstate}
        requestHttpModel.getApproveListData(whitchPage,type, new OnRequestApproveListListener() {
            @Override
            public void OnRequestApproveListSuccess(List<ApproveListBean> approveListBeen) {
                if(whitchPage==1){
                    doPullDownRefresh(approveListBeen);
                }else{
                    doPullUpLoad(approveListBeen);
                }
            }

            @Override
            public void OnRequestApproveListFail(String message) {
                ToastUtil.show(mAct,message);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    //根据位置自动判断是否加载更多数据
    private void loadMoreData(){
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
            Log.d("test", "loading executed");
            boolean isRefreshing = swipeRefreshLayout.isRefreshing();
            if (isRefreshing) {
                adapter.notifyItemRemoved(adapter.getItemCount());
                return;
            }
            if (!isLoading) {
                isLoading = true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        whitchPage +=1;
                        getData();
                        Log.d("test", "load more completed");
                        //     isLoading = false;
                    }
                }, 0);
            }
        }
    }

    public void doPullDownRefresh(List<ApproveListBean> approveList) {
        data.addAll(approveList);
        adapter.notifyDataSetChanged();
        adapter.setHasMoreData(true);
        swipeRefreshLayout.setRefreshing(false);
        adapter.notifyItemRemoved(adapter.getItemCount());
        //防止页数太少不加载了，滑动的时候会自动判断，判断静止的时候就自己去加载了，0表示不滑动了
        if(recyclerView.getScrollState()==0){
            loadMoreData();
        }
    }


    public void doPullUpLoad(List<ApproveListBean> approveList) {
        isLoading = false;
        swipeRefreshLayout.setRefreshing(false);
        if(approveList==null||approveList.size()==0){
            adapter.setHasMoreData(false);
        }else{
            data.addAll(approveList);
        }
        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(adapter.getItemCount());
    }



    //积分类型0：回馈积分 1：现金积分
    public static ApproveListFragment instatant (int approveType){

        ApproveListFragment fragment = new ApproveListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("approve_type", approveType);
        fragment.setArguments(bundle);
        return fragment;
    }

}
